package com.pocketmenu.ui;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.pocketmenu.business.Constants;
import com.pocketmenu.business.ItemListCursorAdapter;
import com.pocketmenu.business.RestaurantCursorAdapter;
import com.pocketmenu.business.SensorTestActivity;
import com.pocketmenu.persistence.Category;
import com.pocketmenu.persistence.CategoryDataSource;
import com.pocketmenu.persistence.Item;
import com.pocketmenu.persistence.ItemDataSource;
import com.pocketmenu.persistence.OrderDataSource;
import com.pocketmenu.persistence.Restaurant;
import com.pocketmenu.persistence.RestaurantDataSource;
import com.pocketmenu.persistence.SQLiteHelper;
//import org.openintents.sensorsimulator.hardware.Sensor;
//import org.openintents.sensorsimulator.hardware.SensorManagerSimulator;

public class ItemListActivity extends Fragment {
	
	private boolean filterChecked = false;			
	private int idSelectedCategory = 0;
	private SimpleCursorAdapter itemAdapter;
	private List<Category> categoryListTemp;
	public static List<Restaurant> restaurantList = new ArrayList<Restaurant>();	
	private SimpleCursorAdapter restaurantAdapter;
//	private SensorManagerSimulator s2=null;
	private SensorManager s2=null;
	private SensorTestActivity sensores=null;
	private Item platoRandom=null;
	
	public ListViewItemOnTouchListener touchListener;
	protected boolean waitingForThread;
	protected String prueba;		
	
	private Activity getCurrentActivity()
	{
		return getActivity();
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//      SensorManager s=(SensorManager) getSystemService(SENSOR_SERVICE);
     
		if (container == null) {            
            return null;
        }				                             
        
		View fragmentView;
		
		if(Constants.idRestaurant != 0)
		{
			fragmentView = inflater.inflate(R.layout.activity_item_list, container, false);			
			loadItemListView(fragmentView);
			acelerometro();									 
		}
		else
		{
			fragmentView = inflater.inflate(R.layout.activity_restaurant,  container, false);				
			loadRestaurantListView(fragmentView);
		}
		//load item listview                        
        
        return fragmentView;
	}
	
	
	private void acelerometro(){
		s2= (SensorManager) this.getCurrentActivity().getSystemService(Context.SENSOR_SERVICE);
	      sensores = new SensorTestActivity(s2) {
				
	    	  @Override
				public void onShakex() {
				
					int numPlatoRandom=(int) Math.round(Math.random()*(Constants.itemListTemp.size()-1));
					
					platoRandom=Constants.itemListTemp.get(numPlatoRandom);
					 //Dialog
					AlertDialog.Builder builder = new AlertDialog.Builder(getCurrentActivity());
					
			        
					builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();				
						}
					});
			        
			        builder.setPositiveButton("Agregar a orden", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//aqui borrar todos los items de la orden
							OrderDataSource orderDatasource = new OrderDataSource(getCurrentActivity());		
							
							orderDatasource.open();
							Constants.idOrder = orderDatasource.addOrderItem(platoRandom.getPrice(), platoRandom.getId(), Constants.idOrder);
							orderDatasource.close();
						}
					});
			        
			        builder.setTitle("Plato elegido:"+platoRandom.getName());
			        builder.setMessage(platoRandom.getDescription());    
			        builder.show();
				}

				@Override
				public void onShakey() {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onShakez() {
					// TODO Auto-generated method stub
					Thread networkThread = new Thread() {
			      	    @Override
			      	    public void run() {
				      	      
				  	    	//request       	    
				      	    String metodo = "masPedidos";	
				      	    SoapObject request= new SoapObject(Constants.namespace, metodo);
				      	    request.addProperty("idRestaurante", Constants.idRestaurant);
				
				      	    //modelo sobre
				      	    SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);
				      	    sobre.dotNet = true;
				
				      	    sobre.setOutputSoapObject(request);
				
				      	    //transporte
				      	    HttpTransportSE transporte= new HttpTransportSE(Constants.url,10000);	          
				      	    transporte.debug = true;           
				      	  ItemDataSource id= new ItemDataSource(getCurrentActivity());
							id.open();
				      	    //llamada
				      	    try {
				      	    	transporte.call(Constants.namespace+metodo, sobre);
					   			
					   			//resultado
					   			SoapPrimitive resultado = (SoapPrimitive) sobre.getResponse();
					   			String respuesta=resultado.toString();
								String[] restaurantesWeb = respuesta.split(";");
								
					   			for(int i=0;i<restaurantesWeb.length;i++){
					   				if(i==4){
					   					i=restaurantesWeb.length;
					   				}
									String[] restauranteWebActual=restaurantesWeb[i].split("\\*");								
//					   				Item nuevo= new Item();
//					   				
//					   				nuevo.setId(Integer.parseInt(restauranteWebActual[0]));
//					   				nuevo.setName(restauranteWebActual[1]);
//					   				nuevo.setDescription(restauranteWebActual[2]);
//					   				nuevo.setPrice(Integer.parseInt(restauranteWebActual[3]));
//					   				nuevo.setIdRestaurant(Integer.parseInt(restauranteWebActual[4]));
//					   				nuevo.setIdCategory(Integer.parseInt(restauranteWebActual[5]));
//					   				nuevo.setRecomended(Boolean.parseBoolean(restauranteWebActual[6]));
//					   				nuevo.setNumPedido(Integer.parseInt(restauranteWebActual[7]));
//									
									
									prueba+= "- " + restauranteWebActual[1]+ "\n";
									
									id.create(restauranteWebActual[1], restauranteWebActual[2], Integer.parseInt(restauranteWebActual[3]), 1000, Integer.parseInt(restauranteWebActual[4]), Boolean.parseBoolean(restauranteWebActual[6]));
									
					   				
								}
					   			
						   		
					   			} catch (Exception e) {
				   					Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
					   				e.printStackTrace();
					   				
					   			}
				      	    waitingForThread = false;
				      	  Category a=new Category();
							a.setName("Mas pedidos");
							a.setId(1000);
							categoryListTemp.add(a);
							filterChecked=true;
							
//				      	  reloadItemLisView();
//				      	  id.delete(toDelete)
				      	id.close();
			      	    }	      	      
			  	    };
			  	    networkThread.start();
			  	    
			  	    while(waitingForThread){	      	    	
			  	    }
					AlertDialog.Builder builder = new AlertDialog.Builder(getCurrentActivity());
					
					builder.setTitle("Platos mas pedidos!");   
//			    	builder.setView(restauranDetailView);
					
			    	builder.setMessage(prueba);
			    	builder.setCancelable(true);
			        builder.show();
			        prueba="";
				}
			};
			s2.registerListener(sensores,
	  	        s2.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
	  	        SensorManager.SENSOR_DELAY_NORMAL);
	}
	

	
	@Override
	public void onStop() {
		if(s2!=null && sensores!=null){
			s2.unregisterListener(sensores);
		}
	    super.onStop();
	}
	
	
	
//	private void acelerometro(){
//		 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//	      StrictMode.setThreadPolicy(policy);
//	      s2=  SensorManagerSimulator.getSystemService(getActivity(), "sensor");
//	      
//	      s2.connectSimulator();
//	      
//	      sensores = new SensorTestActivity(s2) {
//				
//				@Override
//				public void onShake() {
//				
//					int numPlatoRandom=(int) Math.round(Math.random()*(Constants.itemListTemp.size()-1));
//					
//					platoRandom=Constants.itemListTemp.get(numPlatoRandom);
//					 //Dialog
//					AlertDialog.Builder builder = new AlertDialog.Builder(getCurrentActivity());
//					
//			        
//			        builder.setNeutralButton("Cancelar", new DialogInterface.OnClickListener() {
//						
//						public void onClick(DialogInterface dialog, int which) {
//							dialog.dismiss();			
//						}
//					});
//			        
//			        builder.setTitle("Plato elegido:"+platoRandom.getName());
//			        builder.setMessage(platoRandom.getDescription());    
//			        builder.show();
//					
//					
//				}
//			};
//			s2.registerListener(sensores,
//	  	        s2.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
//	  	        SensorManager.SENSOR_DELAY_NORMAL);
//	}
//	
//
//	
//	@Override
//	public void onStop() {
//		if(s2!=null && sensores!=null){
//			s2.unregisterListener(sensores);
//		}
//	    super.onStop();
//	}
	/*
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_list);        
        
        //Load extras
        Intent intent = getIntent();
        idRestaurant = intent.getIntExtra(Constants.EXTRA_RESTAURANT_ID, 0);
        idOrder = intent.getIntExtra(Constants.EXTRA_ORDER_ID, 0);
        
        //Load message
        loadMessage(intent);        
        
        //load item listview                        
        loadItemListView();
    }*/       
        
    private Cursor getItems(boolean filter, int idCategory)
    {
    	ItemDataSource itemDatasource = new ItemDataSource(getCurrentActivity());
        itemDatasource.open();
        
        Cursor cursor; 
        
        cursor = itemDatasource.getItems(Constants.idRestaurant, filter, idCategory);
        
        cursor.moveToFirst();        
        
        Constants.itemListTemp = new ArrayList<Item>();
        
	    while (!cursor.isAfterLast()) {
	      Item temp = ItemDataSource.cursorToObject(cursor);
	      Constants.itemListTemp.add(temp);
	      cursor.moveToNext();
	    }
	    cursor.moveToFirst();
        itemDatasource.close();
	    return cursor;
    }
    
    private void loadItemListView(View view)
    {
        ListView listView = (ListView) view.findViewById(R.id.lvItemList);
        
        //listview header
        View headerView = View.inflate(getCurrentActivity(), R.layout.header_item_list, null);       
        setHeaderValues(headerView, filterChecked);
        listView.addHeaderView(headerView);        
                       
        loadItemAdapter();
        listView.setAdapter(itemAdapter);              
    }

    private void reloadItemLisView()
    {
        itemAdapter.changeCursor(getItems(filterChecked, idSelectedCategory));            
    }
    
    private void loadItemAdapter()
    {
    	//Load adapter
    	String[] from = new String[]{SQLiteHelper.COLUMN_ITEM_NAME, SQLiteHelper.COLUMN_ITEM_PRICE, SQLiteHelper.COLUMN_ITEM_DESCRIPTION, SQLiteHelper.COLUMN_ITEM_RECOMENDED};        
        int[] to = new int[]{R.id.tvItemName,R.id.tvItemPrice, R.id.tvItemDescription, R.id.imgStar};
        
        Cursor cursor = getItems(filterChecked, idSelectedCategory);     
        
        touchListener = new ListViewItemOnTouchListener(ListViewItemOnTouchListener.ACTION_SWIPE_RIGHT) {
			
			@Override
			public void onClick(View v) {
				viewItemDescription(v);		    			
			}

			@Override
			public void onSwipe(View v, int action) {
				 if(action == ListViewItemOnTouchListener.ACTION_SWIPE_RIGHT)
					 addItemToOrder(v);
				
			}
		};
        
        itemAdapter = new ItemListCursorAdapter(getCurrentActivity(), R.layout.single_item, cursor, from, to, touchListener);            
    }
    
    private void viewItemDescription(View v){    	
    	ListView itemList = (ListView)v.getParent();
    	
    	// -1 to ignore header
    	int selectedIndex = itemList.getPositionForView(v) - 1;    	    	
    	
	    Item item = Constants.itemListTemp.get(selectedIndex);		    
	    
	    //Dialog
	    showSimpleDialog(item.getName(), item.getDescription());	
    	        
    }  
    
    public void addItemToOrder(View v)
	{				
		ListView parentListview = (ListView) v.getParent();
		int index = parentListview.getPositionForView(v);
		
		//-1 to ignore header
		Item selectedItem = Constants.itemListTemp.get(index - 1);    	
		
		OrderDataSource orderDatasource = new OrderDataSource(getCurrentActivity());		
		
		orderDatasource.open();
		Constants.idOrder = orderDatasource.addOrderItem(selectedItem.getPrice(), selectedItem.getId(), Constants.idOrder);
		orderDatasource.close();

		Toast.makeText(getCurrentActivity(), "Agregado a tu pedido :)", Toast.LENGTH_SHORT).show();		
	}
    
    private void showSimpleDialog(String title, String message)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());    	    	    	
        builder.setNeutralButton("Cancelar", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();				
			}
		});
        
        builder.setTitle(title);
        builder.setMessage(message);    
        builder.show();
	}
    
    private void setHeaderValues(View headerView, boolean filter)
    {
    	//Preferences filter
    	CheckBox cbFilterTemp = (CheckBox) headerView.findViewById(R.id.cbFiltrar);
    	cbFilterTemp.setChecked(filter);    	    	
    	
    	//Category
    	CategoryDataSource datasource = new CategoryDataSource(getCurrentActivity());
    	datasource.open();
    	Cursor categoryCursor = datasource.getAll(Constants.idRestaurant);
    	
    	categoryListTemp = new ArrayList<Category>();
    	categoryCursor.moveToFirst();
    	while(!categoryCursor.isAfterLast())
    	{    	
    		Category categoryTemp = datasource.cursorToObject(categoryCursor);
    		categoryListTemp.add(categoryTemp);
    		categoryCursor.moveToNext();
    	}
    	idSelectedCategory = categoryListTemp.get(0).getId();
    	
    	categoryCursor.moveToFirst();
    	
    	String[] from = new String[]{SQLiteHelper.COLUMN_CATEGORY_NAME};        
        int[] to = new int[]{android.R.id.text1};
    	
    	@SuppressWarnings("deprecation")
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(getCurrentActivity(), android.R.layout.simple_spinner_item, categoryCursor, from, to);
    	
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	
    	Spinner spCategoryTemp = (Spinner) headerView.findViewById(R.id.spCategoria);
    	spCategoryTemp.setAdapter(adapter);    	
    	
    	spCategoryTemp.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView,
					int position, long id) {
				idSelectedCategory = categoryListTemp.get(position).getId();	
				reloadItemLisView();				
			}

			public void onNothingSelected(AdapterView<?> parentView) {
				// TODO Auto-generated method stub
				
			}
		});
    	
    	datasource.close();
    }
    
    private Cursor getRestaurants()
    {
		RestaurantDataSource restaurantDatasource = new RestaurantDataSource(getCurrentActivity());
		restaurantDatasource.open();
				
		restaurantDatasource.updateRestaurantsWithDistance(getCurrentLocation());
		
		Cursor cursor = restaurantDatasource.getAllAsCursor();
		
		cursor.moveToFirst();
      	  					    	                 
        restaurantList = new ArrayList<Restaurant>();
        
	    while (!cursor.isAfterLast()) {
	      Restaurant temp = restaurantDatasource.cursorToObject(cursor);
	      restaurantList.add(temp);
	      cursor.moveToNext();
	    }
	    
	    cursor.moveToFirst();	    
        restaurantDatasource.close();
	    return cursor;
    }
    
    private void loadRestaurantListView(View view)
    {
        ListView listView = (ListView) view.findViewById(R.id.lvRestaurants);
                               
        loadRestaurantAdapter();
        listView.setAdapter(restaurantAdapter);              
    }

    private void reloadRestaurantLisView()
    {
        ListView listView = (ListView) getView().findViewById(R.id.lvRestaurants);
                               
        loadRestaurantAdapter();
        listView.setAdapter(restaurantAdapter);              
    }
    
    private void loadRestaurantAdapter()
    {
    	//Load adapter    	
    	String[] from = new String[]{SQLiteHelper.COLUMN_RESTAURANT_NAME, SQLiteHelper.COLUMN_RESTAURANT_DESCRIPTION};    	
      	int[] to = new int[]{R.id.tvRestaurantName,R.id.tvRestaurantDescription};              	
      	
        Cursor cursor = getRestaurants();    
        
        ListViewItemOnTouchListener touchListener = new ListViewItemOnTouchListener(ListViewItemOnTouchListener.ACTION_SWIPE_RIGHT) {
			
			@Override
			public void onSwipe(View v, int action) {
				if(action == ListViewItemOnTouchListener.ACTION_SWIPE_RIGHT)
					bListItems_Click(v);
			}
			
			@Override
			public void onClick(View v) {
				TabLayoutActivity tabLayout = TabLayoutActivity.getInstance();
				if(Constants.idRestaurant == 0)
					tabLayout.verDetalle(v);
				
			}
		};
        				
        restaurantAdapter = new RestaurantCursorAdapter(getCurrentActivity(), R.layout.single_restaurant, cursor, from, to, touchListener);            
    }		
    
    private Location getCurrentLocation(){

    	LocationManager locationManager = (LocationManager) getCurrentActivity().getSystemService(Context.LOCATION_SERVICE);

		Criteria criteria = new Criteria();
    	criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    	criteria.setAccuracy(Criteria.NO_REQUIREMENT);
    	String bestProvider = locationManager.getBestProvider(criteria, true);    			
    	
    	return locationManager.getLastKnownLocation(bestProvider);
    }
    
    private void bListItems_Click(View view)
    {    	
    	if(Constants.idRestaurant == 0)
    	{
	    	ListView parentListview = (ListView) view.getParent();
	    	TabLayoutActivity tabLayout = TabLayoutActivity.getInstance();
	    	tabLayout.restaurantSelectedIndex = parentListview.getPositionForView(view);
	    	
	    	Restaurant resturantTemp = ItemListActivity.restaurantList.get(tabLayout.restaurantSelectedIndex);
	    	Constants.idRestaurant = resturantTemp.getId();
	    	
	    	tabLayout.setTitle(resturantTemp.getName());
	    	
	    	tabLayout.reloadCurrentTab = true;
	    	tabLayout.onTabChanged("ItemListTab");
	    	tabLayout.reloadCurrentTab = false;
    	}
    }
    
    public void cbFiltrar_Click(View view)
    {
    	CheckBox temp = (CheckBox) view;
    	filterChecked = temp.isChecked();
    	
    	//Intent intentTemp = getIntent();
    	//intentTemp.removeExtra(Constants.EXTRA_MESSAGE);
    	//intentTemp.putExtra(Constants.EXTRA_ORDER_ID, idOrder);
    	//startActivity(intentTemp);
    	//finish();
    }

    
    
    /*
    public void rlItem_Click(View v){
    	
    	LinearLayout singleItem = (LinearLayout)v.getParent();
    	
    	ListView itemList = (ListView)singleItem.getParent();
    	
    	// -1 to ignore header
    	selectedIndex = itemList.getPositionForView(singleItem) - 1;    	    	
    	
	    Item item = Constants.itemListTemp.get(selectedIndex);		    
	    
	    //Dialog
    	AlertDialog.Builder builder = new AlertDialog.Builder(getCurrentActivity());    	
    	    	
        builder.setNeutralButton("Cancelar", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();				
			}
		});
        
        builder.setTitle(item.getName());        
        builder.setMessage(item.getDescription());                
        builder.show();
    }   */	
    
    
}
